package gl.web.onlinedoc.util;

import java.io.File;

public class FileSort {

	public static char getChar(String str, int idx) {
		if (str.length() <= idx) {
			return '\'';
		}
		return str.charAt(idx);
	}

	public static int myCompare(String lhs, String rhs) {
		int lLen = lhs.length();
		int rLen = rhs.length();
		int idx = 0;
		while (idx < lLen && idx < rLen) {
			if (getChar(lhs, idx) == getChar(rhs, idx)) {
				++idx;
			} else {
				if (getChar(lhs, idx) > getChar(rhs, idx)) {
					return 1;
				} else {
					return -1;
				}
			}
		}
		if (lLen == rLen) {
			return 0;
		} else {
			if (lLen > rLen) {
				return 1;
			} else {
				return -1;
			}
		}
	}

	public static void QSort(String[] strArray, int low, int high) {
		if (low < high) {
			int first = low;
			int last = high;
			String key = strArray[first];
			while (first < last) {
				while (first < last && myCompare(strArray[last], key) >= 0) {
					--last;
				}

				strArray[first] = strArray[last];

				while (first < last && myCompare(strArray[first], key) <= 0) {
					++first;
				}

				strArray[last] = strArray[first];
			}
			strArray[first] = key;
			QSort(strArray, low, first - 1);
			QSort(strArray, first + 1, high);
		}
	}

	public static void main(String[] args) {

		int index = 0;
		String[] fileNameArray = new String[100];

		// 读目录的

		File[] files = new File("F:\\demo\\jfinal_demo\\WebRoot\\doc").listFiles();
		for (File file : files) {
			fileNameArray[index++] = file.getName();
		}

		// 测试

//		fileNameArray[index++] = "ka";
//		fileNameArray[index++] = "2.1";
//		fileNameArray[index++] = "2.2";
//		fileNameArray[index++] = "吴";
//		fileNameArray[index++] = "1.2(吴嘉a)";
//		fileNameArray[index++] = "1.2.1(吴嘉)";
//		fileNameArray[index++] = "(哈哈)";
//		fileNameArray[index++] = "1.1";
//		fileNameArray[index++] = "(高新园)";
//		fileNameArray[index++] = ".";
//		fileNameArray[index++] = "1.1.0";
//		fileNameArray[index++] = "z";
//		fileNameArray[index++] = "_";
//		fileNameArray[index++] = "(地铁)";
//		fileNameArray[index++] = "Z";
//		fileNameArray[index++] = "a";
//		fileNameArray[index++] = "A";
//		fileNameArray[index++] = "a8";
//		fileNameArray[index++] = "A8";
//		fileNameArray[index++] = "k";
//		fileNameArray[index++] = "ak";
//		fileNameArray[index++] = "嘉";
//		fileNameArray[index++] = "K";

		System.out.println("排序前:");
		int i = 0;
		for (i = 0; i < index; ++i) {
			System.out.println(fileNameArray[i]);
		}

		QSort(fileNameArray, 0, index - 1);
		System.out.println("排序后:");
		for (i = 0; i < index; ++i) {
			System.out.println(fileNameArray[i]);
		}

	}
}
